const knexLib = require('knex');

const config = {
  client: 'mysql2',
  connection: {
    host: '152.136.59.218',
    user: 'project',
    password: '123123123',
    database: 'project',
    charset: 'utf8mb4',
  },
  pool: {
    min: 2,
    max: 10,
    // 连接失效后会自动重试，Knex 本身无内置重连机制，需要自己写逻辑
    // 这里主要是配置连接池大小
  },
  acquireConnectionTimeout: 10000, // 10秒连接超时
};

let knex = null;

// 简单的重连机制
async function createKnexConnection(retries = 5, delay = 2000) {
  for (let i = 0; i < retries; i++) {
    try {
      const instance = knexLib(config);
      // 试连接：执行简单查询
      await instance.raw('select 1+1 as result');
      console.log('数据库连接成功');
      return instance;
    } catch (error) {
      console.error(`数据库连接失败，第 ${i + 1} 次重试...`, error.message);
      if (i < retries - 1) {
        await new Promise(res => setTimeout(res, delay));
      } else {
        throw new Error('数据库连接失败，重试次数用尽');
      }
    }
  }
}

async function initKnex() {
  if (!knex) {
    knex = await createKnexConnection();
  }
  return knex;
}

module.exports = {
  initKnex,
  getKnex: () => knex,
};
